<template>
  <!-- photosManagement 相册管理 -->
  <page-meta :page-style="'overflow:' + (showSharePopup ? 'hidden' : 'visible')"></page-meta>
  <PageContainer>
    <view class="container">
      <Header title="相册管理" :is-box-shadow="false" v-model="headerHeight" />
      <!-- 解决if页面跳动 -->
      <view class="tabsBox" :style="`top: ${headerHeight}px;`">
        <Tabs v-if="tabsShow" v-model="currentTab">
          <TabNav tabBarColor="#3762E1" ref="tabNavRef" />
          <template v-for="v in tabDataList" :key="v.id">
            <TabsItem :name="v.name" :value="v.id"></TabsItem>
          </template>
        </Tabs>
      </view>

      <Paglist
        v-model="dataList"
        :is-init-api="false"
        :parame="parame"
        @register="register"
        :is-show-loadmore="dataList.length > 1"
      >
        <template #customEmpty>
          <view class="EmptyBox disFlxCC">
            <image :src="phothsEmptyIcon" style="width: 224rpx; height: 224rpx" />
            <view class="fz-14 mt-15">快来创建你的第一个相册吧</view>
          </view>
        </template>
        <template v-for="v in dataList" :key="v.id">
          <PhotoItem
            :item="v"
            @openModel="openModel"
            @removeTop="removeTop(v.id)"
            @openShare="openShare"
          />
        </template>
      </Paglist>

      <view v-if="tabsShow && !tabDataList.length && !dataList.length" class="EmptyBox disFlxCC">
        <image :src="phothsEmptyIcon" style="width: 224rpx; height: 224rpx" />
        <view class="fz-14 mt-15">快来创建你的第一个相册吧</view>
      </view>

      <HoverBall :headerHeight="headerHeight" :boxWidth="63" :boxHeight="125">
        <view class="fz-10 py-12">
          <view class="disFlxCC" @click="addPhotos">
            <image :src="addPhothsIcon" style="width: 56rpx; height: 56rpx" />
            <view>新建相册</view>
          </view>
          <view class="disFlxCC mt-15" @click="editGroup">
            <image :src="editGroupIcon" style="width: 56rpx; height: 56rpx" />
            <view>管理分组</view>
          </view>
        </view>
      </HoverBall>

      <ShowModal
        v-model="modalOptions.modalVisible"
        :title="modalOptions.modalTitle"
        :confirm-text="modalOptions.confirmText"
        @confirm="confirm"
      >
        <template #content>
          <view class="px-35">{{ modalOptions.modalContent }}</view>
        </template>
      </ShowModal>
    </view>
  </PageContainer>

  <CustomShare v-model:visible="showSharePopup" @register="handleCustomShareRegister" />
</template>

<script lang="ts" setup>
  /**  photosManagement  相册管理 */
  import PageContainer from '@/components/PageContainer/index.vue';
  import CustomShare from '@/components/CustomShare/index.vue';
  import { useCustomShare } from '@/components/CustomShare/hooks/useCustomShare';
  import { photoAlbumGroupList, newPhotoAlbumList } from '@/api/photoAlbum';
  import type { PhotoAlbumGroupListResult, PhotoAlbumListResult } from '@/api/photoAlbum/types';
  import { topPhotoAlbum, removeTopPhotoAlbum, forceDelPhotoAlbum } from '@/api/admin/index';
  import Header from '@/components/Header/index.vue';
  import { getCurrentInstance, nextTick, provide, reactive, ref, unref, watch } from 'vue';
  import Tabs from '@/components/tabs/index.vue';
  import TabsItem from '@/components/tabs/item.vue';
  import TabNav from '@/components/tabs/nav.vue';
  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';
  import PhotoItem from './components/photoItem.vue';
  import { onHide, onShareAppMessage, onShow } from '@dcloudio/uni-app';
  import HoverBall from './components/hoverBall.vue';
  import { svgToDataUrl } from '@/utils/index';
  import { phothsEmptySVG, addPhothsSVG, editGroupSVG } from './components/photosIcon';
  import { navigateTo } from '@/router';
  import ShowModal from '@/components/ShowModal/index.vue';
  import { PhotosModalType } from '@/enums/admin';
  import { createMiniCode } from '@/utils/dynamicConfig';
  import { Toast } from '@/utils/index';
  import { useAppStoreWithOut } from '@/store/modules/app';
  import { addAppShareLog } from '@/api';
  import { useAppShare } from '@/hooks/core/useAppShare';
  import { getAlbumPosterData } from './components/utils';

  const { setWxSharePath } = useAppShare();

  const { globalConfig } = useAppStoreWithOut();
  const phothsEmptyIcon = svgToDataUrl(phothsEmptySVG);
  const addPhothsIcon = svgToDataUrl(addPhothsSVG);
  const editGroupIcon = svgToDataUrl(editGroupSVG);
  const headerHeight = ref(0);
  const currentTab = ref<number>();
  const tabDataList = ref<PhotoAlbumGroupListResult[]>([]);

  const { createShareQuery } = useAppShare();

  const showSharePopup = ref(false);
  const [
    customShareRegister,
    {
      setMenuWxShareOptions,
      setWxShareOptions,
      setShareLogId,
      setPosterDrawData,
      setInternalLinkOptions,
    },
  ] = useCustomShare({
    buttons: {
      share: true,
      poster: true,
      copyLink: true,
      insertOffiaccount: true,
    },
    disableds: {
      shortLink: true,
    },
  });

  function handleCustomShareRegister(e: any) {
    customShareRegister(e);
    setMenuWxShareOptions({
      imageUrl: globalConfig?.comShareOptions.shareImg,
      path: setWxSharePath({ name: 'photoAlbumManage' }),
      title: '相册',
    });
  }

  provide('api', (obj: any) => {
    return newPhotoAlbumList(obj);
  });

  const dataList = ref<PhotoAlbumListResult[]>([]);
  const parame = reactive({
    belongId: 0,
  });

  const [register, { refresh }] = useConList();

  watch(currentTab, (val) => val && tabsChange(val));
  function tabsChange(id: number) {
    currentTab.value = id;
    parame.belongId = id;
    refresh && refresh();
  }

  const tabsShow = ref(false); // 更新tabs
  const _this = getCurrentInstance();
  async function getGroup() {
    const list = await photoAlbumGroupList();
    tabsShow.value = true;
    tabDataList.value = list;
    if (list.length) {
      const currentObj = ref<any>({});
      const currentIndex = ref<number>(0);
      list.forEach((v, i) => {
        if (v.id === unref(currentTab)) {
          currentObj.value = {
            name: v.name,
            value: v.id,
            disabled: false,
          };
          currentIndex.value = i;
        }
      });
      currentTab.value = unref(currentObj)?.value ?? list[0].id; // 当前选中对象
      parame.belongId = currentTab.value as number;

      // 修复回显时, if导致tabs位置初始化，需调用内部点击事件滚动到当前选中位置
      if (unref(currentObj)?.value) {
        await nextTick();

        (_this?.refs['tabNavRef'] as any)?.onItem?.(unref(currentObj), unref(currentIndex));
      }
    }
  }

  onShow(() => {
    getGroup();
    unref(currentTab) && refresh && refresh();
  });
  // 解决tabs， 新增 || 排序不更新 以及出现两个选中bug
  onHide(() => {
    tabsShow.value = false;
  });

  function addPhotos() {
    let currentObj = unref(tabDataList).find((v) => v.id === unref(currentTab));
    uni.setStorageSync('_CLICK_INFO', {
      type: 'checkedPhotosGroup',
      ...currentObj,
    });
    navigateTo({ name: 'addPhotos', options: {} });
  }
  function editGroup() {
    navigateTo({ name: 'photosGroup' });
  }

  // 操作二次确认弹窗
  const modalOptions = reactive({
    id: 0,
    type: PhotosModalType.ISTOP,
    modalVisible: false,
    modalTitle: '提示',
    modalContent: '置顶首页后，该相册将在首页第一位 展示，原已置顶的相册将自动后移。',
    confirmText: '确认置顶',
  });
  function openModel(type: PhotosModalType, id: number) {
    modalOptions.id = id;
    modalOptions.modalVisible = true;
    modalOptions.type = type;
    if (type === PhotosModalType.ISTOP) {
      modalOptions.modalTitle = '提示';
      modalOptions.modalContent =
        '置顶首页后，该相册将在首页第一位 展示，原已置顶的相册将自动后移。';
      modalOptions.confirmText = '确认置顶';
    } else {
      modalOptions.modalTitle = '确认删除相册?';
      modalOptions.modalContent = '相册删除后,相册中的照片将无法恢复';
      modalOptions.confirmText = '确认';
    }
  }
  function confirm() {
    modalOptions.type === PhotosModalType.ISTOP
      ? setTop(modalOptions.id)
      : removePhotos(modalOptions.id);
  }

  // 置顶
  function setTop(id: number) {
    topPhotoAlbum(id).then(() => {
      Toast('置顶成功');
      refresh && refresh();
    });
  }
  // 取消置顶
  function removeTop(id: number) {
    removeTopPhotoAlbum(id).then(() => {
      Toast('置顶已取消');
      refresh && refresh();
    });
  }
  // 删除相册
  function removePhotos(id: number) {
    forceDelPhotoAlbum(id).then(() => {
      refresh && refresh();
    });
  }

  const shareCache = new Map<number, { codeImg: string; shareLogId: number; posterImg: string }>(
    [],
  );

  // 打开分享
  const openShare = async (item: PhotoAlbumListResult) => {
    const shareCacheItem = shareCache.get(item.id);
    const describe = '分享一个相册给你，来看看吧~';
    if (!shareCacheItem) {
      uni.showLoading({ title: '分享参数准备中...', mask: true });
    }
    await setWxShareOptions([
      {
        path: setWxSharePath({ name: 'photoAlbumDetails', options: { id: item.id as number } }),
        imageUrl: item?.originalCoverUrl ?? item?.coverUrl, // 封面
        title: item.name,
      },
      {
        path: setWxSharePath({ name: 'photoAlbumDetails', options: { id: item.id as number } }),
        imageUrl: item?.originalCoverUrl ?? item?.coverUrl, // 封面
        title: describe,
      },
    ]);
    setInternalLinkOptions({
      name: 'photoAlbumDetails',
      options: { id: item.id as number },
    });
    const routeQuery = createShareQuery({ id: item.id });
    let shareLogId = shareCacheItem?.shareLogId;
    let codeImg = shareCacheItem?.codeImg;
    if (!shareCache.has(item.id)) {
      const res = await addAppShareLog({
        path: 'photoAlbumDetails',
        query: JSON.stringify(routeQuery),
      });
      shareLogId = res.id;
      codeImg = await createMiniCode({ shareLogId });
      const posterImgs = await setPosterDrawData(
        getAlbumPosterData(
          { name: item.name, coverUrl: item?.originalCoverUrl ?? item?.coverUrl, describe },
          codeImg,
        ),
      );
      shareCache.set(item.id, { codeImg, shareLogId, posterImg: posterImgs[0] });
      uni.hideLoading();
    } else {
      await setPosterDrawData([shareCacheItem?.posterImg || '']);
    }

    setShareLogId(shareLogId as number);
    showSharePopup.value = true;
  };
  onShareAppMessage(() => ({}));
</script>

<style lang="scss" scoped>
  .tabsBox {
    height: 76rpx;
    background-color: #fff;
    position: sticky;
    z-index: 10;
  }
  .EmptyBox {
    height: 70vh;
  }
</style>
